package org.dreamwork.jasmine2.web.client;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-4-25
 * Time: 下午4:47
 */
public class UserAgentParser {
    public static final Pattern IE_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?\\(compatible; MSIE ([\\d\\.]+);\\sWindows( NT )?\\s*([\\d\\.]+);(\\sWOW64;)?.*?\\sTrident\\/([\\d\\.]+).*$");
    public static final Pattern OPERA_PATTERN =
            Pattern.compile ("^Opera\\/.*?Presto\\/([\\d\\.]+)\\sVersion\\/([\\d\\.]+).*$");
    public static final Pattern FIREFOX_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?Gecko\\/([\\d]+).*?Firefox\\/([\\d\\.]+).*$");
    public static final Pattern CHROME_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?\\(.*?AppleWebKit\\/([\\d\\.\\+]+)\\s*\\(KHTML, like Gecko\\).*?Chrome\\/([\\d\\.]+).*?Safari\\/([\\d\\.]+).*$");
    public static final Pattern ANDROID_MOBILE_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?\\(Linux; U; Android.*?AppleWebKit\\/([\\d\\.\\+]+)\\s*\\(KHTML, like Gecko\\).*?(Version\\/([\\d\\.]+))? Mobile Safari\\/[\\d\\.]+.*?", Pattern.CASE_INSENSITIVE);
    public static final Pattern IPHONE_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?\\((iPhone|iPad).*?AppleWebKit\\/([\\d\\.]+)\\s*\\(KHTML, like Gecko\\).*?Version\\/([\\d\\.]+) Mobile\\/.*?Safari\\/[\\d\\.]+.*?", Pattern.CASE_INSENSITIVE);
    public static final Pattern SAFARI_PATTERN =
            Pattern.compile ("^Mozilla\\/.*?AppleWebKit\\/([\\d\\.]+)\\s*\\(KHTML, like Gecko\\).*?Version\\/([\\d\\.]+).*?Safari\\/[\\d\\.]+.*?$", Pattern.CASE_INSENSITIVE);

    public UserAgent parse (String expression) {
        Matcher m = IE_PATTERN.matcher (expression);
        if (m.matches ())
            return IEParser.parse (m);

        m = OPERA_PATTERN.matcher (expression);
        if (m.matches ())
            return OperaParser.parse (m);

        m = FIREFOX_PATTERN.matcher (expression);
        if (m.matches ())
            return FireFoxParser.parse (m);

        m = CHROME_PATTERN.matcher (expression);
        if (m.matches ())
            return ChromeParser.parse (m);

        m = ANDROID_MOBILE_PATTERN.matcher (expression);
        if (m.matches ())
            return AndroidMobileParser.parse (m);

        m = IPHONE_PATTERN.matcher (expression);
        if (m.matches ())
            return IPhoneParser.parse (m);

        m = SAFARI_PATTERN.matcher (expression);
        if (m.matches ())
            return SafariParser.parse (m);

        if (expression.contains ("MSIE 6")) {
            UserAgent ua = new UserAgent (expression);
            ua.setType (BrowserType.InternetExplorer);
            ua.setVersion (new Version (6, 0));
            ua.setKernel (new RenderKernel (RenderkernelType.Trident, Version.UNKNOWN));
            ua.setOs (OSParser.parseOS (expression));
        }

        return new UserAgent.UnknownUserAgent (expression);
    }
}